package com.jinlong.manage.impl;

import com.jinlong.common.api.BaseApiService;
import com.jinlong.common.redis.BaseRedisService;
import com.jinlong.common.token.TokenUtils;
import com.jinlong.constants.Constants;
import com.jinlong.constants.DBTableName;
import com.jinlong.constants.MQInterfaceType;
import com.jinlong.dao.UserDao;
import com.jinlong.entity.UserEntity;
import com.jinlong.manage.UserServiceManage;
import com.jinlong.mq.roducer.RegisterMailboxProducer;
import com.jinlong.untils.DataUtils;
import com.jinlong.untils.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class UserServiceManageImpl extends BaseApiService implements UserServiceManage {
    @Autowired
    private UserDao userDao;
    @Autowired
    RegisterMailboxProducer registerMailboxProducer;
    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private BaseRedisService baseRedisService;
    @Value("${messages.queue}")
    private String MESSAGE_QUEUE;
    @Override
    public void regist(UserEntity userEntity) throws JSONException {
        userEntity.setCreated_time(DataUtils.getTimestamp());
        userEntity.setUpdate_time(DataUtils.getTimestamp());
        userEntity.setPass_word(md5PassWordSalt(userEntity.getPhone(),userEntity.getPass_word()));
        userDao.save(userEntity, DBTableName.TABLE_MB_USER);
        ActiveMQQueue mqQueue = new ActiveMQQueue(MESSAGE_QUEUE);



        String mailMessage =  mailMessage(userEntity.getEmail(),userEntity.getUser_name());
        log.info("###regist() 注册邮件发送报文mailMessage{}",mailMessage);
        registerMailboxProducer.send(mqQueue,mailMessage);
    }


    @Override
    public Map<String,Object> login(UserEntity userEntity) {
        String pwd = userEntity.getPass_word();
        String phone = userEntity.getPhone();
        String passWord = md5PassWordSalt(phone, pwd);
        UserEntity uerPhoneAndPwd = userDao.getUerPhoneAndPwd(phone, passWord);
        if(uerPhoneAndPwd == null){
            return setResultError("账号或密码错误！");
        }
        String openid = userEntity.getOpenid();
        if(!StringUtils.isEmpty(openid)){
            userDao.UpdateUserOpenid(openid,DataUtils.getTimestamp(),uerPhoneAndPwd.getId());
        }
        String token = setLoginToken(uerPhoneAndPwd.getId());
        /*Long id = uerPhoneAndPwd.getId();
        baseRedisService.set(token,id+"", Constants.USER_TOKEN_TERMVALIDITY);*/
        return setResultSuccessData(token);
    }

    @Override
    public Map<String, Object> getUser(String token) {
        String userId = baseRedisService.get(token);
        if(StringUtils.isEmpty(userId)){
            return setResultError("用户已过期");
        }
        long parseLong = Long.parseLong(userId);
        UserEntity userInfo = userDao.getUserInfo(parseLong);
        userInfo.setPass_word(null);
        return setResultSuccessData(userInfo);
    }



    private String mailMessage(String email,String userName) throws JSONException {
        JSONObject root = new JSONObject();
        JSONObject header = new JSONObject();
        header.put("interfaceType", MQInterfaceType.SMS_MAIL);
        JSONObject content = new JSONObject();

        content.put("mail",email);

        content.put("username",userName);
        root.put("header",header);
        root.put("content",content);

        return root.toString();
    }

    @Override
    public String md5PassWordSalt(String phone, String passWord) {
        String newStr =  MD5Util.MD5(phone+passWord);
        return newStr;
    }

    @Override
    public Map<String, Object> findLogin(String openid) {
        UserEntity userEntity = userDao.findOpenId(openid);
        if(userEntity == null){
            return setResultError("没有关联到用户");
        }
        // 自动登录
        String token = setLoginToken(userEntity.getId());
        return setResultSuccessData(token);
    }

    private String setLoginToken(Long userId) {
        // 生成对应的token
        String token = tokenUtils.getToken();
        // key为自定义令牌,用户的userId作作为value 存放在redis中
        baseRedisService.set(token, userId + "", Constants.USER_TOKEN_TERMVALIDITY);
        return token;
    }

}
